import { defineStore } from "pinia";

import {
    getWhiteListApi,
    addWhiteListApi,
    updateWhiteListApi,
    delWhiteListApi
} from '@/Api/WhiteList'
import EventBus from "@/utils/EventBus";
import { useCommon } from "./Common";
const CommonStore = useCommon()

export const useWhiteList = defineStore("whiteList", {
    state: (): WhiteListState => {
        return {
            loading: false,
            searchForm: {
                groupName: '',
                specimenName: '',
                current: 1,
                pageNo: 1,
                pageSize: 20,
                total: 0,
                pageSizeOptions: ['20', '30', '50', '100'],
                showSizeChanger: true,
                showTotal(total: number) { return `共${total}条` },
                onChange(pageNo: number, pageSize: number) {
                    this.current = pageNo
                    this.pageNo = pageNo
                    this.pageSize = pageSize
                }
            },
            addForm: {} as WhiteList,
            editForm: {} as WhiteList,
            tableData: []
        };
    },
    actions: {
        async getWhiteList() {
            this.loading = true
            try {
                const valueToLabelMap = CommonStore.deviceOptions.reduce((acc, obj) => {
                    acc[obj.value] = obj.label;
                    return acc;
                }, {} as any);
                const data = await getWhiteListApi(this.searchForm) as any
                if (data) {
                    this.tableData = data.white
                    this.tableData.forEach((item, index) => {
                        item.index = (this.searchForm.pageNo! - 1) * this.searchForm.pageSize! + index + 1
                        item.deviceNames = item.serials.map((value: any) => valueToLabelMap[value]).toString();
                    })
                    this.searchForm.total = data.total[0].total
                }
            } finally {
                this.loading = false
            }
        },
        async addWhiteList() {
            const data = await addWhiteListApi(this.addForm) as any
            if (!data) {
                this.getWhiteList()
                EventBus.emit('AddSuccess')
            }
        },
        async editWhiteList() {
            const data = await updateWhiteListApi(this.editForm) as any
            if (!data) {
                this.getWhiteList()
                EventBus.emit('UpdateSuccess')
            }
        },
        async delWhiteList(record: any) {
            const data = await delWhiteListApi(record) as any
            if (!data) {
                this.getWhiteList()
                EventBus.emit('DeleteSuccess')
            }
        }
    },
});